﻿using System;
using MyLib;

namespace Billing2
{
    public partial class Checker : MyThread
    {
        /*
        Reports are to be locked on the 9th of every billing quarter at 23 59 HRS. 
        (9th December lock September to November Period)
        (9th March lock December to February Period) 
        (9th June lock March to May Period) 
        (9th September lock June to August Period)
        */

        Schedule schedule_lock_report = new Schedule(3600, true);
        void lock_report()
        {
            if (!schedule_lock_report.Expired)
                return;

            int year = DateTime.Now.Year;
            DateTime date1 = new DateTime(year, 12, 9).AddDays(1);
            DateTime date2 = new DateTime(year, 9, 9).AddDays(1);
            DateTime date3 = new DateTime(year, 6, 9).AddDays(1);
            DateTime date4 = new DateTime(year, 3, 9).AddDays(1);

            if (DateTime.Now.Date >= date1)
            {
                LockMonth(year, 11);
                LockMonth(year, 10);
                LockMonth(year, 9);
            }
            else if (DateTime.Now.Date >= date2)
            {
                LockMonth(year, 8);
                LockMonth(year, 7);
                LockMonth(year, 6);
            }
            else if (DateTime.Now.Date >= date3)
            {
                LockMonth(year, 5);
                LockMonth(year, 4);
                LockMonth(year, 3);
            }
            else if (DateTime.Now.Date >= date4)
            {
                LockMonth(year, 2);
                LockMonth(year, 1);
                LockMonth(year - 1, 12);
            }
        }

        public void LockMonth(int year, int month)
        {
            int? BillPeriodID = Common.db.SelectInt(@"
                SELECT ID
                FROM BillPeriod
                WHERE StartDate >= @StartDate
                    and StartDate < @EndDate
                    and Locked = 0
                ", new DateTime(year, month, 1)
                , (new DateTime(year, month, 1)).AddMonths(1));
            if (BillPeriodID != null)
            {
                EPPLog.Logger.Info(String.Format("LockMonth: {0}-{1}", year, month));
                Common.db.Exec(@"
                    UPDATE BillPeriod
                    SET Locked = 1
                    WHERE ID = @ID
                    ", BillPeriodID.Value);

                Common.db.Exec(@"
                    UPDATE BillReportRepository
                    SET Locked = 1
                    WHERE BillPeriodID = @ID
                    ", BillPeriodID.Value);
            }
        }
    }
}
